<template>
  <div
    ref="tabElementRef"
    v-ripple
    class="tab-item rounded-t-lg ml-1 position-relative"
    :class="{
      'tab-error': tab.state.error,
      'is-dragging': dragState?.type === 'dragging'
    }"
    :data-testid="`tab-${tab.id}`"
    :style="style"
    @contextmenu="handleContextMenu"
  >
    <div class="d-flex w-100 align-center overflow-hidden" :title="tab.title || tab.url">
      <v-progress-circular
        v-if="tab.nav.isLoading && shouldShowIcon"
        class="mr-2"
        indeterminate
        :size="iconSize"
        :width="2"
      />
      <v-icon v-else-if="tab.icon" class="mr-2" :icon="tab.icon" />
      <v-avatar
        v-else-if="shouldShowIcon"
        class="mr-2 pointer-none"
        :icon="tab.state.error ? mdiFileDocumentRemoveOutline : mdiTab"
        :image="tab.favicon"
        rounded="0"
        :size="iconSize"
      />
      <!-- 媒体播放指示器 -->
      <v-btn
        v-if="tab.state.isPlaying"
        color=""
        density="comfortable"
        :icon="tab.state.isMuted ? mdiVolumeOff : mdiVolumeHigh"
        size="x-small"
        variant="text"
        @click.stop="onToggleMute"
        @mousedown.stop
      />
      <span class="text-no-wrap overflow-hidden flex-1-1-0 w-0" data-testid="tab-title">{{
        tab.title || tab.url || t('newTab')
      }}</span>
      <v-btn
        v-if="shouldShowCloseButton"
        color=""
        density="comfortable"
        :icon="mdiClose"
        size="x-small"
        variant="text"
        @click.stop="onCloseTab"
        @mousedown.stop
      />
    </div>
    <DropIndicator
      v-if="dropState.type === 'drag-over' && dropState.closestEdge"
      :edge="dropState.closestEdge"
      offset="-3px"
      :style="dropColor"
    />
  </div>
</template>

<script lang="ts" setup>
import {
  mdiClose,
  mdiCloseBoxMultiple,
  mdiContentCopy,
  mdiDockLeft,
  mdiDockRight,
  mdiFileDocumentRemoveOutline,
  mdiLinkVariant,
  mdiOpenInNew,
  mdiPin,
  mdiTab,
  mdiVolumeHigh,
  mdiVolumeOff
} from '@mdi/js'
import { useI18n } from 'vue-i18n'
import {
  calculateMouseDistanceToElement,
  handleResolvedDrop,
  resolveBrowserTabOrGroup
} from '@/composables/dragAndDrop/dragDropUtil'
import { useDragHandle } from '@/composables/dragAndDrop/useDragHandle'
import { useDropHandle } from '@/composables/dragAndDrop/useDropHandle'
import { showContextMenu } from '@/utils/contextMenuHelper'
import { useSidebarStore } from '@/windows/layoutBrowser/stores/sidebar'
import { useTabStore } from '@/windows/layoutBrowser/stores/tab'
import { useTabWidthStore } from '@/windows/layoutBrowser/stores/tabWidth'
import DropIndicator from '../common/DropIndicator.vue'

const { t } = useI18n()
const sidebarStore = useSidebarStore()

const tabStore = useTabStore()
const props = defineProps<{
  group?: F2.tab.Group
  tab: F2.tab.Entity
  tabWidth: number
  isActive: boolean
}>()

const dropColor = computed(() => {
  if (!props.group?.id) return

  const group = tabStore.tabs.find(item => item.id === props.group?.id) as F2.tab.Group
  if (!group) return

  return { backgroundColor: group.color }
})

/**
 * 拖拽数据类型
 * 包含标识符和标签页信息，用于拖拽操作中的数据传递
 */
export type TabDragData = {
  data: F2.tab.TabOrGroup // 标签页对象
  inGroupId?: number // 如果在分组内，则记录分组ID
}

// const { tabElementRef, dragState } = useDragAndDrop(props)
const tabElementRef = ref<HTMLElement>()

const { dragState } = useDragHandle<TabDragData>({
  el: tabElementRef,
  nativeDrag: true,
  dragType: 'browser-tab',
  dragData: {
    data: props.tab,
    inGroupId: props.group?.id
  }
})

const tabWidthStore = useTabWidthStore()

const { dropState } = useDropHandle({
  el: tabElementRef,
  acceptedTypes: ['browser-tab', 'browser-tab-group'],
  allowedEdges: ['left', 'right'],
  canDrop: (source, input) => {
    const group = source['browser-tab-group']

    // 分组不允许嵌套
    if (!tabElementRef.value || (group !== undefined && props.group)) {
      return false
    }

    // 检查分组内的拖拽边界限制
    if (props.group) {
      const groupElement = tabElementRef.value.parentElement?.parentElement
      if (groupElement) {
        const distance = calculateMouseDistanceToElement(input, groupElement)
        if (
          distance.left < tabWidthStore.dragBoundary.leftMin ||
          distance.right < tabWidthStore.dragBoundary.rightMin
        ) {
          return false
        }
      }
    }

    return true
  },
  onDrop: (source, edge, isExternal) => {
    const resolved = resolveBrowserTabOrGroup(source)
    handleResolvedDrop(
      resolved,
      props.tab.id,
      edge === 'right',
      isExternal,
      tabStore.moveTabRelativeToAnother
    )
  }
})

const iconSize = computed(() => (props.group?.id ? 14 : 16))

const style = computed(() => {
  const py = props.group?.id ? '3px' : '5px'
  const baseStyle = {
    width: `${props.tabWidth}px`,
    padding: `${py} 3px ${py} 8px`
  }

  // 为活动状态和非活动状态添加背景色
  return props.isActive
    ? {
        ...baseStyle,
        backgroundColor: 'rgb(var(--v-theme-tab-active))',
        boxShadow: '0 -2px 2px rgba(var(--v-theme-on-surface), 0.1)'
      }
    : {
        ...baseStyle,
        backgroundColor: 'rgb(var(--v-theme-tab-base))',
        color: 'rgb(var(--v-theme-on-tab-base))'
      }
})

// 定义宽度阈值
const MIN_WIDTH_FOR_BOTH = 70 // 同时显示图标和关闭按钮的最小宽度

const shouldShowIcon = computed(() => {
  if (props.isActive) {
    // 激活状态：优先关闭按钮，只有宽度足够时才显示图标
    return props.tabWidth >= MIN_WIDTH_FOR_BOTH
  } else {
    // 非激活状态：优先图标，总是显示图标
    return true
  }
})

const shouldShowCloseButton = computed(() => {
  if (props.isActive) {
    // 激活状态：优先显示关闭按钮，总是显示
    return true
  } else {
    // 非激活状态：优先图标，只有宽度足够时才显示关闭按钮
    return props.tabWidth >= MIN_WIDTH_FOR_BOTH
  }
})

/**
 * 关闭标签页
 */
function closeTab(tabIds: number[]) {
  tabStore.closeTabs(tabIds)
}

/**
 * 关闭当前标签页
 */
function onCloseTab() {
  closeTab([props.tab.id])
}

/**
 * 切换静音状态
 */
function toggleMute() {
  _pre_.tab.toggleMute(props.tab.webContentsId)
}

function onToggleMute() {
  toggleMute()
}

// 常量定义
const NEW_TAB_TITLE = '新标签页'

/**
 * 检查标签页是否可以移动到边栏
 */
function canMoveToSidebar(tab: F2.tab.Entity): boolean {
  if (tab.nav.isLoading) {
    console.warn('页面正在加载中，无法移动到边栏')
    return false
  }

  if (!tab.title || tab.title === NEW_TAB_TITLE || tab.title.trim() === '') {
    console.warn('页面标题无效，无法移动到边栏')
    return false
  }

  return true
}

async function handleContextMenu(event: MouseEvent) {
  event.preventDefault()
  event.stopPropagation()
  const allTabs = tabStore.getAllTabsLinear()
  const tab = props.tab
  const currentTabIndex = allTabs.findIndex(t => t.id === tab.id)

  await showContextMenu([
    {
      label: `${t('tab.contextMenu.duplicate')} (&D)(D)`,
      icon: mdiContentCopy,
      cb: () => {
        _pre_.browser.addTab({
          url: props.tab.url,
          title: tab.title,
          source: {
            type: 'tab',
            id: tab.id,
            originalUrl: tab.url
          }
        })
      }
    },
    {
      label: `${t('tab.contextMenu.copyUrl')} (&C)(C)`,
      icon: mdiLinkVariant,
      cb: () => {
        navigator.clipboard
          .writeText(tab.url)
          .then(() => {
            console.log('URL已复制到剪贴板:', tab.url)
          })
          .catch(error => {
            console.error('复制URL失败:', error)
          })
      }
    },
    {
      label: `${t('tab.contextMenu.moveToSidebar')} (&P)(P)`,
      icon: mdiPin,
      type: 'submenu',
      submenu: [
        {
          label: t('tab.contextMenu.moveToLeftSidebar'),
          icon: mdiDockLeft,
          type: 'normal',
          cb: () => sidebarStore.moveTabToSidebar(tab)
        },
        {
          label: t('tab.contextMenu.moveToRightSidebar'),
          icon: mdiDockRight,
          type: 'normal',
          cb: () => sidebarStore.moveTabToSidebar(tab, true)
        }
      ],
      enabled: canMoveToSidebar(tab)
    },
    {
      label: `${t('tab.contextMenu.openInNewWindow')} (&N)(N)`,
      icon: mdiOpenInNew,
      cb: () => {
        _pre_.browser.create([tab.id])
      }
    },
    {
      label: `${tab.state.isMuted ? t('tab.contextMenu.unmute') : t('tab.contextMenu.mute')} (&M)(M)`,
      icon: tab.state.isMuted ? mdiVolumeHigh : mdiVolumeOff,
      cb: toggleMute,
      visible: tab.state.isPlaying || false
    },
    { type: 'separator' },
    {
      label: `${t('tab.contextMenu.close')} (&W)(W)`,
      icon: mdiClose,
      cb: () => closeTab([tab.id])
    },
    {
      label: `${t('tab.contextMenu.closeOthers')} (&O)(O)`,
      cb: () => {
        const otherTabIds = allTabs.filter(t => t.id !== tab.id).map(t => t.id)
        if (otherTabIds.length > 0) {
          closeTab(otherTabIds)
        }
      }
    },
    {
      label: `${t('tab.contextMenu.closeToRight')}  (&R)(R)`,
      cb: () => {
        const rightTabIds = allTabs.slice(currentTabIndex + 1).map(t => t.id)
        if (rightTabIds.length > 0) {
          closeTab(rightTabIds)
        }
      },
      visible: currentTabIndex < allTabs.length - 1
    },
    {
      label: `${t('tab.contextMenu.closeAll')} (&A)(A)`,
      icon: mdiCloseBoxMultiple,
      cb: () => tabStore.closeAllTabs()
    }
  ])
}
</script>

<style scoped>
.tab-item {
  font-size: 12px;
  font-weight: 400;
  transition:
    background-color 0.2s ease,
    box-shadow 0.2s ease,
    border-color 0.2s ease;
}

/* 加载状态样式 - 移除额外UI，因为已有加载图标 */

/* 错误状态样式 */
.tab-item.tab-error {
  border-left: 2px solid rgb(var(--v-theme-error));
}

.tab-item.tab-error span {
  color: rgb(var(--v-theme-error));
  text-decoration: line-through;
  opacity: 0.8;
}

.tab-item.tab-error .v-avatar {
  color: rgb(var(--v-theme-error)) !important;
}

.tab-item.is-dragging {
  opacity: 0.5;
}

/* 加载动画已移除，使用内置的加载图标 */

.tab-item.v-chip.v-chip--size-small :deep(.v-avatar) {
  margin-left: -2px;
  --v-avatar-height: 17px;
}

.tab-item :deep(.v-chip__content) {
  flex: 1 1 auto;
  width: 0;
  white-space: nowrap;
}

.tab-item.slide-y-reverse-transition-move {
  transition: all 0.2s !important;
}

.pointer-none {
  pointer-events: none;
}
</style>
<i18n>
{
  "zhHans": {
    "newTab": "新建标签页",
    "tab": {
      "contextMenu": {
        "reload": "重新加载",
        "duplicate": "复制标签页",
        "pin": "固定标签页",
        "moveToSidebar": "移动到边栏",
        "moveToLeftSidebar": "移动到左侧边栏",
        "moveToRightSidebar": "移动到右侧边栏",
        "openInNewWindow": "在新窗口打开",
        "mute": "静音标签页",
        "unmute": "取消静音",
        "close": "关闭标签页",
        "closeOthers": "关闭其他标签页",
        "closeToRight": "关闭右侧标签页",
        "copyUrl": "复制链接地址",
        "closeAll": "关闭所有页面"
      }
    }
  },
  "en": {
    "newTab": "New Tab",
    "tab": {
      "contextMenu": {
        "reload": "Reload",
        "duplicate": "Duplicate Tab",
        "pin": "Pin Tab",
        "moveToSidebar": "Move to Sidebar",
        "moveToLeftSidebar": "Move to Left Sidebar",
        "moveToRightSidebar": "Move to Right Sidebar",
        "openInNewWindow": "Open in New Window",
        "mute": "Mute Tab",
        "unmute": "Unmute Tab",
        "close": "Close Tab",
        "closeOthers": "Close Other Tabs",
        "closeToRight": "Close Tabs to the Right",
        "copyUrl": "Copy Link Address",
        "closeAll": "Close All Tabs"
      }
    }
  }
}
</i18n>
